/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Model;

import Controller.LogManager;
import Controller.ProductManager;
import java.io.IOException;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author pauld
 */
@WebServlet(name = "EditProduct", urlPatterns = {"/EditProduct"})
public class EditProduct extends HttpServlet {
    private static String productIndex = null,
            name = null,
            synopsis = null,
            genre = null,
            type = null,
            price = null,
            status = "0";
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        //update the database then returns the result in a variable
        int result = ProductManager.editProduct(name, synopsis, genre, type, price, status, productIndex);
        
        switch (result) {
            //if the product was successfully edited
            case 1: 
                LogManager.logEvent("EditProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.INFO, "Edit Product Successful: " + name, request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
                response.sendRedirect("admin/editProduct.jsp?id=" + name.replace(" ", "_").replace("'", "") + "&status=1");
                break;
            //if the product already exists in the db
            case 0: 
                LogManager.logEvent("EditProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.WARNING, "Edit Product Unsuccessful - Product Already Exists: " + name, request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
                response.sendRedirect("admin/editProduct.jsp?id=" + name.replace(" ", "_").replace("'", "") + "&status=-1");
                break;
            //if there was an error in the db
            case -1: 
                LogManager.logEvent("EditProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.SEVERE, "Edit Product Unsuccessful - Databse Error", request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
                response.sendRedirect("admin/editProduct.jsp?id=" + name.replace(" ", "_").replace("'", "") + "&status=-2");
                break;
        }
    }
    
    //method for checking the user inputs
    //returns true if user inputs are valid and fals otherwise
    private static boolean checkInput(HttpServletRequest request){
        //get the form values and store them on the variables
        name = request.getParameter("name");
        synopsis = request.getParameter("synopsis");
        genre = request.getParameter("genre");
        type = request.getParameter("type");
        price = request.getParameter("price");
        status = request.getParameter("status");
        
        //checks the form inputs using regex
        String regexXSS = "[<(.*?)>]",    //blacklist
                regexAlpha = "[A-Za-b ]",
                regexNum = "[0-9.]";
        Pattern pAlpha = Pattern.compile(regexAlpha, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE),
                pNum = Pattern.compile(regexNum, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE),
                pXSS = Pattern.compile(regexXSS, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher mName = pXSS.matcher(name),
                mPrice = pNum.matcher(price),
                mGenre = pAlpha.matcher(genre),
                mType = pAlpha.matcher(type);
        boolean resultName = mName.find(),
                resultPrice = mPrice.find(),
                resultGenre = mGenre.find(),
                resultType = mType.find();
        
        //check the length of the user inputs and checks the regex
        if( (name.length() > 0 && name.length() <= 45) && 
            (synopsis.length() > 0 && synopsis.length() <= 254) && 
             genre.length() != 0 && 
             type.length() != 0 &&
                !resultName &&
                resultPrice &&
                resultGenre &&
                resultType)
            return true;
        else
        {
            LogManager.logEvent("EditProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.WARNING, "Edit Product Unsuccessful - Invalid Input", request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
            return false;
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        productIndex = request.getParameter("product");
        
        //before adding product to database the inputs are checked
        if( checkInput(request) )
            processRequest(request, response);
        else
            response.sendRedirect("admin/editProduct.jsp?id=" + productIndex + "&status=0");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        productIndex = request.getParameter("product");
        
        //before adding product to database the inputs are checked
        if( checkInput(request) )
            processRequest(request, response);
        else
            response.sendRedirect("admin/editProduct.jsp?id=" + productIndex + "&status=0");
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
    
}
